package videoCapture;

import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

public class VideoP2P2 implements Runnable {
	public static int PORT = 5556;
	private CanvasFrame canvas;
	private IplImage image;
	private int width = 640;
	private int height = 480;
	private String title = "chat2";

	private DatagramSocket dataSocket;
	private DatagramPacket dataPacket;
	private byte receiveByte[];
	private static int BUFSIZE = 1024;

	ByteArrayOutputStream bout;
	ByteArrayInputStream bin;
	
	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public VideoP2P2() throws SocketException {
		// TODO Auto-generated constructor stub
		dataSocket = new DatagramSocket(PORT);
		receiveByte = new byte[1024];
		dataPacket = new DatagramPacket(receiveByte, receiveByte.length);

		canvas = new CanvasFrame(title);
		canvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		canvas.setCanvasSize(width, height);
		bout = new ByteArrayOutputStream();
	//	bin = new ByteArrayInputStream(null);
	}

	public void display() throws IOException, InterruptedException {
		boolean flag = true;
		while (true) {
			try{
				image = recive();
				
				if (image != null) {
					if (image.width() != width || image.height() != height) {
						width = image.width();
						height = image.height();
						canvas.setCanvasSize(width, height);
						flag = !flag;
					}
					canvas.showImage(image);
				}
			}catch(Exception e ){
				e.printStackTrace();
			}
			
			Thread.sleep(40);
		}
	}

	int sum = 0;

	public IplImage recive() throws IOException {
		 bout = new ByteArrayOutputStream();
		BufferedImage bimage = null;
		int bufSize = 0;
		int i = 0;
		// SampleModel sm = new MultiPixelPackedSampleModel(0,480,640,3);
		
		while (i == 0)// 无数据，则循环
		{
			dataSocket.receive(dataPacket);
			i = dataPacket.getLength();
			bufSize += i;
			// 接收数据
//			 System.out.println("server " + i);
			if (i > 0) {
				bout.write(dataPacket.getData(), 0, i);
				i = 0;// 循环接收
				
				continue;
			}
			
			break;
		}

		// DataBuffer dBuffer = new DataBufferByte(bout.toByteArray(), width *
		// height);
		// WritableRaster wr = Raster.createInterleavedRaster(dBuffer, width,
		// height, width, 1, new int[] { 0 }, null);
		// ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
		// ColorModel cm = new ComponentColorModel(cs, false, false,
		// Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
		// BufferedImage bi = new BufferedImage(cm, wr, false, null);

		bin = new ByteArrayInputStream(bout.toByteArray());
		
		try {
			bimage = ImageIO.read(bin);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		bout.reset();
		bin.close();
		// sum++;
//		System.out.println("bufSize " + bufSize);
		return IplImage.createFrom(bimage);
	}

	public IplImage recive2() throws IOException {
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		BufferedImage bimage = null;
		int bufSize = 0;
		int i = 0;
		// SampleModel sm = new MultiPixelPackedSampleModel(0,480,640,3);
		while (i == 0)// 无数据，则循环
		{
			dataSocket.receive(dataPacket);
			i = dataPacket.getLength();
			bufSize += i;
			if (i > 0) {
				bout.write(dataPacket.getData(), 0, i);
				i = 0;// 循环接收
				continue;
			}
			break;
		}
		DataBuffer db = new DataBufferByte(bout.toByteArray(), 480 * 640 * 3);
		WritableRaster raster = WritableRaster.createInterleavedRaster(db, 640,
				480, 640 * 3, 3, new int[] { 2, 1, 0 }, null);

		ColorModel colorModel = new ComponentColorModel(
				ColorSpace.getInstance(ColorSpace.CS_sRGB),
				new int[] { 8, 8, 8 }, false, false, Transparency.OPAQUE,
				DataBuffer.TYPE_BYTE);

		bimage = new BufferedImage(colorModel, raster, false, null);

//		System.out.println("bufSize " + bufSize);
		return IplImage.createFrom(bimage);
	}

	public void run() {
		try {
			this.display();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		VideoP2P2 chat = new VideoP2P2();
		// chat.display();
		Thread thread = new Thread(chat);
		thread.start();
	}
}
